<template>
  <div>
    <van-field v-model="formData.username" label="账号"/>
    <van-field v-model="formData.password" label="密码"/>
    <van-button type="danger" size="small" @click="onLogin">登 录</van-button>
  </div>
</template>

<script lang="ts">
import {defineComponent} from 'vue'
import {b64tohex, hex2b64} from "@/utils/encrypt/Base64.js";
import {RSAKey} from "@/utils/encrypt/Rsa.js";
import {deepClone} from "@/utils/helpers";
import Login from "@/api/modules/Login";
import {Toast} from "vant";
import {setRefreshToken, setToken} from "@/utils/auth";

export default defineComponent({
  name: "Login",
  data() {
    return {
      formData: {
        username: '18277135062',
        password: '111111',
      },
      hasRsaKey: true,
      rsaKey: new RSAKey(),
    }
  },
  created() {
    this.getRsa();
  },
  methods: {
    // 获取rsa秘钥
    async getRsa(toastError = false) {
      try {
        const resp = await Login.getRsa();
        this.rsaKey.setPublic(
            b64tohex(resp.data.modulus),
            b64tohex(resp.data.exponent)
        );
        this.hasRsaKey = true;
        return true;
      } catch (e) {
        console.log(e)
        if (toastError) {
          Toast('请求登录秘钥失败');
        }
      }
      return false;
    },
    async onLogin() {
      if (!this.hasRsaKey) {
        const _r = await this.getRsa(true);
        if (!_r) {
          return;
        }
      }
      let postData = deepClone(this.formData);
      postData.password = hex2b64(this.rsaKey.encrypt(postData.password)); //加密
      Login.clientLoginByWeb(postData)
          .then((resp: any) => {
            if (resp.result) {
              setToken(resp.data.token || '');
              setRefreshToken(resp.data.refreshToken || '');
              // const time = new Date().getTime();
              // sessionStorage.setItem("tokenTime", `${time}`);
              // sessionStorage.setItem("token", resp.data.token);
              sessionStorage.setItem("principalId", resp.data.principalId || '');
              // sessionStorage.setItem("refreshToken", resp.data.refreshToken);
              Toast('登录成功');
            } else {
              Toast(resp.message);
            }
          })
          .catch(err => {
            Toast(err.message);
          });
    }
  }
})
</script>

<style scoped>

</style>